﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace game
{
    public class ShipTraceHandler
    {
        protected Scene scene;
        protected Vector3 initialPosition;

        protected int pSystemNum;
        protected int nextPSystemIndex;
        protected ShipTracePSystem[] pSystems;
        protected Vector3[] pSystemOffsets;

        public ShipTraceHandler(Scene scene, Vector3 initialPosition, int traceSourceNum)
        {
            this.scene = scene;
            this.initialPosition = initialPosition;
            this.pSystemNum = traceSourceNum;

            pSystems = new ShipTracePSystem[pSystemNum];
            pSystemOffsets = new Vector3[pSystemNum];
            nextPSystemIndex = 0;
        }

        public void AddTraceSource(Vector3 offset)
        {
            if (nextPSystemIndex < pSystemNum)
            {
                Vector3 sourcePosition;
                Vector3.Add(ref initialPosition, ref offset, out sourcePosition);

                ShipTracePSystem newSystem = new ShipTracePSystem(scene, sourcePosition);
                newSystem.Initialize();
                pSystems[nextPSystemIndex] = newSystem;

                pSystemOffsets[nextPSystemIndex] = offset;

                nextPSystemIndex++;
            }
        }

        public void Update(GameTime gameTime, Vector3 position, Matrix rotation, Vector3 velocity)
        {
            Vector3 rotatedOffset;
            Vector3 offsetPosition;
            for (int i = 0; i < nextPSystemIndex; i++)
			{
                Vector3.Transform(ref pSystemOffsets[i], ref rotation, out rotatedOffset);
                Vector3.Add(ref position, ref rotatedOffset, out offsetPosition);
                pSystems[i].Update(gameTime, offsetPosition, rotation, velocity);
			}
        }

        public void Draw(GameTime gameTime)
        {
            for (int i = 0; i < nextPSystemIndex; i++)
            {
                pSystems[i].Draw(gameTime);
            }
        }
    }
}
